//是哪个类型
var type = getQueryVariable('type');
//如果没指定，默认选中推荐
if (!type) {
    type = "recommend";
}

//更新用户信息
var userId = null;
//作者评论
var ljc_name = "";
var ljc_tx = "";

//是否正常播放中
var isGoodPlaying = false;
//使用hlsjs框架进行播放
var useHlsJs = true;

/**
 * 自定义请求
 * */
var customRequestUrl = null;
var customRequestParam = null;

var page = 1;
var pageSize = 5;

var speed = 1;
// 播放的列表
var list = [];
var first = true;

var current = 0;
var showVideoTimer;


/**
 * 自动播放控制
 * */
var autoPlayControl =
    {
        value: false,
        enableAutoPlay: function () {
            //启用自动播放
            this.value = true;
        },
        disableAutoPlay: function () {
            this.value = false;
        },
        isAutoPlay: function () {
            //if(true)
            //    return true;
            return this.value;
        }
    };

/**
 * 如果已经点击过了，就隐藏红点
 * */
function hideTopicTipIfHasClick() {
    if (localStorage.getItem("topicTipIfHasClick"))
        $("#topic_tip").hide();
}

/**
 * 点击跳转
 * */
function clickTopic() {
    localStorage.setItem("topicTipIfHasClick", true);
    hideTopicTipIfHasClick();
    //location.href="/ui/short_video_topic/main";
    App.redirect('short_video_topic/main');
}
function clickFollow(){
    App.redirect('short_video/main',{type:'follow'});
}
function clickRecommend(){
    App.redirect('short_video/main',{type:'recommend'});
}
function clickNew(){
    App.redirect('short_video/main',{type:'new'});
}



hideTopicTipIfHasClick();


var mySwiper = new Swiper('.xmvideo.swiper-container', {
    initialSlide: 1,
    direction: 'vertical',
    on: {
        touchStart: function (swiper, event) {
            console.log('Slide change transition started!');
            hideVideo();
        },
        touchEnd: function (swiper, event) {
            console.log('Slide change transition started!');
            showVideo();
        }
    }
})


/**
 * 控制面板
 * */

var progressWrap = document.getElementById("progressWrap");
var showProgress = document.getElementById("showProgress");
var progressBtn = document.getElementById("progressBtn");
var bufferProgress = document.getElementById("bufferProgress");


var progressFlag;

//当前播放中的视频元素
var currentVideoEle = null;

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}


/**
 * 菜单更新选的是那个类别
 * */
function chooseType() {
    if ("author" == type || "search" == type || "custom" == type) {
        var index = getQueryVariable('index');
        var authorData = sessionStorage.getItem('shortVideoCustomData');
        list = JSON.parse(authorData);

        //先初始化，否则数据少的时候，没有这个item会报错
        mySwiper.slideTo(0);
        updateVideoItem();
        mySwiper.slideTo(index);
        updateVideoItem();

        $('.defaultTopNav').hide();
        $('.customDataTopNav').show();


        //自定义查询
        if ("custom" == type) {
            customRequestUrl = sessionStorage.getItem('shortVideoCustomUrl');
            customRequestParam = JSON.parse(sessionStorage.getItem('shortVideoCustomParam'));
            page = customRequestParam.pageIndex + 1;
            pageSize = parseInt(customRequestParam.pageSize);
        } else if ("author" == type)
            page = (list.length / pageSize) + 1;
        //搜索的结果是多少就多少，禁用下拉
        else if ("search" == type) {
            page = null;
        }
    } else {
        var chooseItem = $(".topnav ." + type);
        chooseItem.addClass("active");
        $(chooseItem).find("a").append("<i class=\"underline\"></i>");
    }
}

//更新菜单
chooseType();

var pageNavigationType = Net.navUrlMaping['4'].navigationType;
var fromCode = App.getQueryParam('code');
Net.loadUser(App.device(), fromCode, function (userRes) {
    var userData = userRes.data;
    userId = userData.id;
    App.getResourceLocation(4, userData.icon, function (src) {
        ljc_tx = src;
    });
    ljc_name = userData.nickName;

    //底部导航,漫画小说等
    Net.nav(userId, function (navResult) {
        HTML.renderNav($('.bottom-nav'), navResult.data, pageNavigationType);
    });

    //初始化视频
    getVideo();
    first = false;

    $(".icon_play").show();
});


// 监听 activeIndex 变动
mySwiper.on('slideChange', function () {
    var activeIndex = mySwiper.activeIndex;
    console.log('当前活动 slide 的索引:', activeIndex);
    updateVideoItem();
    //	console.log(list.length);
    if (list.length - mySwiper.activeIndex <= 3) {
        getVideo();
    }
    clearProcess();
});


function getVideo() {
    //首字母大写
    var serviceType = "by" + type.charAt(0).toUpperCase() + type.slice(1);
    var authorId = $('.videouserid').html();

    //禁用自动获取
    if (null == page)
        return;


    var successCall = function (res) {
        if (res.length == 0) {

            if (mySwiper.activeIndex == (list.length - 1))
                Toast("没有更多数据了");
            return;
        }
        list = list.concat(res);
        updateVideoItem();
    };

    //统一的自定义查询，外部决定的
    if (customRequestUrl) {
        customRequestParam.pageIndex = page;
        new Service().getByRequest(customRequestUrl, customRequestParam).then(successCall).catch(res => {
            console.error(res);
        });
    } else {
        new Service().getShortVideoByType(serviceType, userId, page, pageSize, authorId, first).then(successCall).catch(res => {
            console.error(res);
        });
    }
    page++;
}

//上一个更新视图的下标
var lastInfoIndex = -1;

/**
 * 更新信息视图
 * */
function updateInfoView(index) {
    if (lastInfoIndex == index) {
        console.log("视图一样，跳过");
        return;
    }
    lastInfoIndex = index;
    //更新头像
    App.getResourceLocation(4, list[index].authorIcon, function (src) {
        $('.img-avator').prop("src", src);
    });


    $('.bottom-user').html("@" + list[index].authorName);
    $('.challenge-name').html(list[index].cover_type);
    $('.videoid').html(list[index].id);
    $('.videouserid').html(list[index].authorId);
    App.getResourceLocation(4, list[index].verticalCover, function (src) {
        $('.videoimg').html(src);
    });


    $('#ljc_likes').html(App.formatNumber(list[index].likeCount));
    $('#ljc_comment').html(list[index].commentCount);
    $('#ljc_shared').html(App.formatNumber(Math.floor(Math.random() * list[index].likeCount)));


    //标签追加到概要后面
    var tagsHtml = "";
    if (list[index].tags) {
        var tags = list[index].tags.split(",");
        for (var i = 0; i < tags.length; i++) {
            var tag = tags[i];
            var tagHtml = "<span>#" + tag + "</span>";
            tagsHtml += tagHtml;
        }
    }

    $('.bottom-desc').html(list[index].title + tagsHtml);

    videoinfo(list[index].id);

}


// 在需要时清除视频
function clearVideo(player, videoEle) {
    // 释放资源
    if (player) {
        player.destroy();
    }
}

var plnum = 0;

/**
 * 只显示日期
 * */
function showDate(date) {
    date = new Date(date);
    var year = date.getFullYear();
    var month = date.getMonth() + 1; // 注意getMonth()是从0开始的
    var day = date.getDate();

    var dateString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    console.log(dateString);
    return dateString;
}

//载入评论
function commentpost(id) {

    page_pl = 1;
    new Service().getShortVideoComment(id).then(function (data) {
        plnum = 0;
        var html = '';
        if (data == '' || data == '[]') {
            $('.numcommnet').html('无人评论,抢个首评吧！');
            $('#J__chatMsgList').html(html);
            return;
        }
        //numcommnet
        //console.log(res.data.length);
        //plnum = res.data.length+plnum;
        plnum = $('#ljc_comment').html();
        $('.numcommnet').html(plnum + '条评论');
        for (var j in data) {
            var obj = data[j];
            //console.log(obj);
            App.getResourceLocation(4, obj.userIcon, function (src) {
                html += '<li class="others">\
							<a class="avatar"><img src="' + src + '" /></a>\
							<div class="content">\
								<p class="author"><a href="#"><span class="slt">' + obj.userName + '</span></a></p>\
								<div class="msg" id="picbig">\
									' + obj.content + '<span class="pltime">' + showDate(obj.createTime) + '</span>\
								</div>\
							</div>\
						</li>';

                //写入评论区
                $('#J__chatMsgList').html(html);
                gdtop();
            });


            //	console.log(html);
        }


        //window.scrollTo(0, 0);
    });
}


function gdtop() {
    $('.comment').scrollTop(0);
}

//评论发送
$(".J__wchatSubmit").on("click", function () {

    var html = $('.J__wcEditor').html();
    //消息为空
    if (html == '') {
        Toast('您还未输入内容', 2000);
        return false;
    }
    var videoid = $(".videoid").html();
    window.scrollTo(0, 0);
    window.scrollTo(0, document.documentElement.clientHeight);
    $('.J__wcEditor').html('');
    new Service().addShortVideoComment(videoid, userId, html).then(function (data) {
        $(".addpl").attr("src", "../shortVideo/img/add.png");
        var addhtml = '<li class="others">\
							<a class="avatar"><img src="' + ljc_tx + '" /></a>\
							<div class="content">\
								<p class="author"><a href="#"><span class="slt">' + ljc_name + '</span></a></p>\
								<div class="msg" id="picbig">\
									' + html + '<span class="pltime">刚刚</span>\
								</div>\
							</div>\
						</li>';
        $("#J__chatMsgList").prepend(addhtml);
        $('#ljc_comment').html(Number($('#ljc_comment').html()) + 1);
        //console.log(data);
    });
});


/**
 * 评论图标变色
 * */
$(".editor").bind("input propertychange change", function (event) {
    if ($('.J__wcEditor').html().length > 0) {
        $(".addpl").attr("src", "../shortVideo/img/add3.png");
    } else {
        $(".addpl").attr("src", "../shortVideo/img/add.png");
    }
});


/**
 * 打开评论区
 * */
$("#comment").on("click", function () {
    id = $(".videoid").html();
    console.log("评论载入" + id);
    commentpost(id);
    setTimeout(function () {
        $(".wc__footTool-panel").show();
        $(".commenttop").show();
    }, 1000);
    $(".comment").show();
});


/**
 * 关闭评论区
 * */
$(".closecommnet").on("click", function () {
    $(".wc__footTool-panel").hide();
    $(".commenttop").hide();
    $(".comment").hide();
});


/**
 * 跳到主播界面
 * */
$("#usergo").on("click", function () {
    id = $(".videouserid").html();
    //window.location.href = "short_video_user?id=" + id;
    App.redirect('short_video_user', {id: id});
});


/**
 * 关注主播
 * */
$("#avator").on("click", function () {
    var authorId = $(".videouserid").html();
    var isAdd = $('.img-follow').is(':visible')
    new Service().addFollowAuthor(authorId, userId, isAdd).then(function (data) {
        Toast('关注成功', 1000);
        $('.img-follow').hide();
    });
});

/**
 * 收藏视频
 * */
$("#like").on("click", function () {
    $('.icon-shoucang').removeClass('animate__animated animate__flipInX');
    var id = $(".videoid").html();
    var isAdd = 'rgb(255, 255, 255)' == $('.icon-shoucang').css('color');
    new Service().addLikeShortVideo(id, userId, isAdd).then(function (data) {
        if (isAdd) {
            $('.icon-shoucang').css('color', '#f52e2e');
            $('.icon-shoucang').addClass('animate__animated animate__flipInX');
            $('#ljc_likes').html(Number($('#ljc_likes').html()) + 1);
        } else {
            $('.icon-shoucang').css('color', '#FFF');
            $('#ljc_likes').html(Number($('#ljc_likes').html()) - 1);
        }

    });

});


$("#share").on("click", function () {
    Toast('链接复制成功', 2000);


    async function copyTextToClipboard(text) {
        if ('clipboard' in navigator) { // 先检查Clipboard API是否可用
            return await navigator.clipboard.writeText(text)
                .then(() => console.log('Text copied to clipboard'))
                .catch(err => console.error('Could not copy text: ', err));
        } else { // Fallback method
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                var successful = document.execCommand('copy');
                var msg = successful ? 'successfully' : 'unsuccessfully';
                console.log('Fallback: Copying text command was ' + msg);
            } catch (err) {
                console.error('Fallback: Oops, unable to copy', err);
            }
            document.body.removeChild(textArea);
        }
    }

    // 要复制的文本
    var textToCopy = location.href;
    // 使用实例
    copyTextToClipboard(textToCopy);
});


/**
 * 旋转视频
 * */
$("#videoxzsp").on("click", function () {
    //$("#secondBg").toggleClass("videoxzsp");
    //console.log('旋转视频');
});


function videoinfo(id) {
    var authorId = $(".videouserid").html();
    new Service().getShortVideoInfo(userId, id, authorId).then(function (data) {
        if (data.isCollect == 1) {
            $('.icon-shoucang').css('color', '#f52e2e');
        } else {
            $('.icon-shoucang').css('color', '#FFF');
        }
        //关注状态
        if (data.isFollow == 1) {
            $('.img-follow').hide();
        } else {
            $('.img-follow').show();
        }

        //点赞数据
        //$('#ljc_likes').html(data.collectCount);
        //$('#ljc_comment').html(data.commentCount);
    });
}

function Toast(msg, duration) {
    duration = isNaN(duration) ? 3000 : duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText = "width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 40%;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
    document.body.appendChild(m);
    setTimeout(function () {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function () {
            document.body.removeChild(m)
        }, d * 1000);
    }, duration);
}


/**
 * 清除播放进度
 */
function clearProcess() {
    showProgress.style.width = "2px";
    progressBtn.style.left = "2px";
    bufferProgress.style.width = "2px";
}


function showPlayProgress(video) {
    var longVideo = video.duration > 20;
    if (longVideo) {
        $("#progressWrap").show();
    } else {
        $("#progressWrap").hide();
    }
    var percent = video.currentTime / video.duration;
    showProgress.style.width = percent * (progressWrap.offsetWidth) - 2 + "px";
    progressBtn.style.left = percent * (progressWrap.offsetWidth) - 2 + "px";

    //缓存进度
    var bufferPercentAge = video.buffered.end(0) / video.duration;
    bufferProgress.style.width = bufferPercentAge * (progressWrap.offsetWidth) - 2 + "px";

    //剩余没播放毫秒数
    var remainMilli = video.duration - video.currentTime;
    //监听视频结束事件,重复播放
    //console.log("video.currentTime："+video.currentTime+",video.duration："+video.duration+",remainMilli:"+remainMilli);
    //有些视频播放不完，可能资源没上传齐全吧
    var nearCloseMilli = 0.25;
    if (nearCloseMilli > remainMilli) {
        console.log("播放结束");
        //重新设置视频的 currentTime 为 0，并播放
        video.currentTime = 0;
        video.play();
    }
}


/**
 * 更新视频item数据
 * */
function updateVideoItem() {
    //当前正在播放那个
    var currentIndex = mySwiper.activeIndex;

    updateInfoView(currentIndex);

    var itemCount = mySwiper.slides.length;

    //获取当前item数量，如果item的数量小于list，则继续新建item 填充刚好item数量等于list的数量
    var needAddItemCount = list.length - itemCount;
    var simpleItem = $($(".simpleItem")[0]);
    var videoItem = $($(".videoItem")[0]);
    for (var i = 0; i < needAddItemCount; i++) {
        var addItem = simpleItem.clone();
        addItem.attr('id', 'videoId_' + i);
        addItem.show();
        $(".swiper-wrapper").append(addItem);
    }

    var items = $(".swiper-wrapper .swiper-slide");
    items.each(function (index, element) {
        //如果是前，中，下个视频，把item替换成视频item
        var isPrev = index == currentIndex - 1;
        var isCurrent = index == currentIndex;
        var isNext = index == currentIndex + 1;

        //遍历item，如果currentIndex是-1 0  +1的附近的item，填充video数据并开启缓存，如果还是currentIndex 的item 直接添加播放
        if (isPrev || isCurrent || isNext) {
            var isVideoItem = $(items[index]).hasClass('videoItem');
            //如果不是视频组件，先替换成视频组件
            if (!isVideoItem) {
                var newVideoItem = videoItem.clone();
                $(newVideoItem).find("img").attr('id', 'videoId_' + index);
                newVideoItem.show();
                $(items[index]).replaceWith(newVideoItem);
                items[index] = newVideoItem;
                element = $(items[index]);
            }

            // 更新封面
            App.getResourceLocation(4, list[index].verticalCover, function (src) {
                document.getElementById('videoId_' + index).setAttribute("src", src);
            });


            var url = App.getResourceLocationReturn(4, list[index].url);
            //url="https://dancedata.oss-cn-guangzhou.aliyuncs.com/"+list[index].url;
            //url=url.replace("sv9v2/","sv9v3/");

            //如果是当前选中item就播放，上下的就暂停
            if (isCurrent) {
                url = getVideoUrlByVip(url);
                setPlayer(index, url, App.getResourceLocationReturn(4, list[index].verticalCover));

                currentVideoEle = list[index].videoEle;
                //播放中，就隐藏控制组件
                //isPlayingHideControl(currentVideoEle);
                //list[index].videoEle.play();

                var videoIndex = '#videoId_' + index;
                console.log("fffff：" + videoIndex);

                //监听播放按钮，和视频，点击就切换暂停或者播放状态
                //可能会被多次调用，移除之前的点击监听
                var imgEle = $(element).find("img");
                console.log("imgEle html:" + $(imgEle).html());
                imgEle.off('click');
                imgEle.click(function (e) {
                    console.log("点击视频播放" + $(this).attr("id"));
                    playOrPause();
                });

                //如果启用了自动播放
                autoPlayIfEnable(url);

            } else if (isNext) {
            }
            //如果不是，统一判断如果有video，直接删掉video，并把viewo重置view
        } else {
            //清除播放
            if (list[index].player) {
                clearVideo(list[index].player, list[index].videoEle);
                list[index].player = null;
            }
            //替换成简单的item
            var emptyItem = simpleItem.clone();
            emptyItem.attr('id', 'videoId_' + index);
            $(emptyItem).find("img").attr("src", App.getResourceLocationReturn(4, list[index].verticalCover));

            emptyItem.show();
            $(items[index]).replaceWith(emptyItem);
        }
    });

    // 更新视图
    mySwiper.update();
}

/**
 * 判断是否vip来能否播放短视频
 * */
function getVideoUrlByVip(url) {
    //是会员就跳过
    if (App.getUser().vipUser)
        return url;

    function getDaysSince1970() {
        var startDate = new Date(1970, 0, 1); // 1970年1月1日
        var currentDate = new Date();
        var timeDifference = currentDate - startDate;
        var milliSecondsInOneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
        var daysSince1970 = Math.floor(timeDifference / milliSecondsInOneDay);
        return daysSince1970;
    }

    var todayPlayCountKey = "todayPlayCountKey_" + getDaysSince1970();
    var todayPlayCount = localStorage.getItem(todayPlayCountKey);
    if (!todayPlayCount)
        todayPlayCount = 1;
    else
        todayPlayCount++;

    console.log("todayPlayCount：" + todayPlayCount);
    localStorage.setItem(todayPlayCountKey, todayPlayCount);
    //每天免费3个视频
    if (todayPlayCount > 10)
        return url;//"";
    return url;
}

//关闭充值提示
$(".closeVipTip").click(function () {
    $('.to-recharge-win').attr('data-vip', 'false');
});

/**
 * 播放或者暂停video
 */
function playOrPause() {
    console.log("playOrPause");
    if (!checkAllowIsVipPlay())
        return;
    if (currentVideoEle.paused || currentVideoEle.ended) {
        if (currentVideoEle.ended) {
            currentVideoEle.currentTime = 0;
        }
        tryPlay();
    } else {
        currentVideoEle.pause();
        $(".icon_play").show();
    }
}

/**
 * 链接是空的，就是不给播放
 * */
function checkAllowIsVipPlay() {
    var src = $(currentVideoEle).attr("source_src");
    if (!src) {
        $(".icon_play").show();
        //就算是会员，用户猛滑，也是有可能url为空的，再检查下不是会员再提示弹窗
        if (!App.getUser().vipUser) {
            $('.to-recharge-win').attr('data-vip', 'true');
            return false;
        }
    }
    return true;
}

/**
 * 如果是播放中，隐藏播放按钮和loading
 * */
function isPlayingHideControl(video) {
    video.ontimeupdate = function () {
        if (video != currentVideoEle) {
            console.log("ontimeupdate 元素不一样，跳过")
            return;
        }
        if (video.currentTime > 0 && !isGoodPlaying) {
            isGoodPlaying = true;
            //缓存暂时解决方案
            $(".icon_loading").hide();
            $(".icon_play").hide();

            autoPlayControl.enableAutoPlay();
        }
        if (video.currentTime > 0)
            showPlayProgress(video);
    }
};


/**
 * 尝试播放
 * */
function tryPlay() {
    try {
        if (!checkAllowIsVipPlay())
            return;
        console.log("tryPlay:");
        isPlayingHideControl(currentVideoEle);
        //如果用原生的video播放，更换src，需要load一下
        if (!useHlsJs) {
            currentVideoEle.load();
        }
        currentVideoEle.play();
        isGoodPlaying = false;
        console.log("tryPlay after");
        //alert("after");
        $(".icon_play").hide();

        //500毫秒后如果还不是播放状态中，就显示loading
        setTimeout(function () {
            if (!isGoodPlaying) {
                $(".icon_loading").show();
                $(".icon_play").show();
            }
        }, 1500);
    } catch (DOMException) {
        console.log('播放异常：' + error);
        $(".icon_play").show();

        //禁用自动播放
        autoPlayControl.disableAutoPlay();
    }
}

/**
 * 浏览器真正支持
 * */
function browserRealSupportHls() {
    if (App.os() == 'IOS') {
        var browser = App.browser();
        if (browser == 'ucBrowser' || browser == 'baiduboxapp' || browser == 'quark') {
            return false;
        }
    }
    return true;
}

/**
 * @param index 当前下标
 * @param src 电影资源
 * @param poster 封面
 * */
function setPlayer(index, src, poster) {
    var videoEle = document.getElementById('video');
    if ($(videoEle).attr("source_src") == src) {
        console.log("已经设置过了，跳过");
        return;
    }
    if (Hls.isSupported() && browserRealSupportHls()) {
        var player = null;
        //如果已经创建过player就取出来就好了，否则创建一个
        //用同一个video 元素，要先销毁，重新创建
        if (list[index].player)
            list[index].player.destroy();

        player = new Hls();


        // 设置视频源，替换 'your-hls-stream-url.m3u8' 为实际的 HLS 流 URL
        player.loadSource(src);
        player.attachMedia(videoEle);

        player.on(Hls.Events.ERROR, function (event, data) {
            // 在出现错误时执行一些操作
            console.error('HLS Error:', event, data);
        });

        // 设置封面
        videoEle.setAttribute('poster', poster);
        $(videoEle).attr("source_src", src);
    } else if (videoEle.canPlayType('application/vnd.apple.mpegurl')) {
        useHlsJs = false;
        $(videoEle).attr("source_src", src);
        $(videoEle).attr("src", src);
        $(videoEle).attr("poster", poster);
        console.log("videoEle after:" + $(videoEle).html());
    }

    //自动加载
    videoEle.load();
    list[index].player = player;

    list[index].videoEle = videoEle;
}


/**
 * 如果能自动播放，就自动播放
 * */
function autoPlayIfEnable(src) {
    if (autoPlayControl.isAutoPlay()) {
        tryPlay(src);
    }
}

function showVideo() {
    showVideoTimer = setTimeout(function () {
        var src = $(currentVideoEle).attr("source_src");
        //没有视频源，跳过显示，就显示封面就好了
        if (!src) {
            return;
        }
        $("#videoParent").css("opacity", 1);
        $("#video").css("z-index", 2);
    }, 1200);
}

function hideVideo() {
    $("#videoParent").css("opacity", 0);
    $("#video").css("z-index", 2);
}

//监听播放按钮，和视频，点击就切换暂停或者播放状态
$(".icon_play").click(function () {
    console.log("点击播放图标");
    playOrPause();
});

/**
 * 监听时间轴，点击就跳转
 * */
$("#progressWrap").click(function (e) {
    if (currentVideoEle.paused || currentVideoEle.ended) {
        playOrPause();
    }
    var length = e.pageX - progressWrap.offsetLeft;
    var percent = length / progressWrap.offsetWidth;
    console.log("length:" + length);
    console.log("percent:" + percent);
    currentVideoEle.currentTime = percent * currentVideoEle.duration;
    showPlayProgress(currentVideoEle);
});


var pageNavigationType = Net.navUrlMaping['4'].navigationType;


$('.to-recharge-btn').on('click',function(){App.redirect('user/pay',{})});

//搜索
$('.search').on('click', function () {


    function boxCaller($box, dataItem, allData, index) {
        var $html = $($('#box-item-tmp').html());
        $box = $box.find('.box-wrapper');
        $box.data('data', dataItem);
        $box.attr('data-id', dataItem.id);
        $html.find('.box-play-name').html(dataItem.title);
        $html.find('.box-play-num').html(App.formatNumber(dataItem.playCount));
        $html.find('.box-content-img').attr('src', App.getResourceLocationReturn(pageNavigationType, dataItem.verticalCover));

        $box.append($html);
        $box.on('click', function () {
            var $this = $(this);

            sessionStorage.setItem('shortVideoCustomData', JSON.stringify(allData));

            var url = '/ui/short_video/main?type=search&index=' + index;
            //window.location.href = url;
            App.redirect('main', {type: 'search', index: index});
        });
    }

    HTML.openSearchPanel(pageNavigationType, [], function (searchResult) {
        var searchResultData = searchResult.data.data;

        //保存结果，点击的时候可以直接播放
        sessionStorage.setItem('shortVideoCustomData', JSON.stringify(searchResultData));

        $('.search-history-panel').hide();
        var $searchResultList = $('.search-result-list>.box-content-list');
        $searchResultList.html('');

        var dataLen = searchResultData.length;
        for (var i = 0; i < dataLen; i++) {
            var dataItem = searchResultData[i];
            var $boxItemHtml = $($('#box-content-item-tmp').html());
            $searchResultList.append($boxItemHtml);

            boxCaller($boxItemHtml, dataItem, searchResultData, i);
        }
    });


});


//定时更新状态栏界面
setInterval(function () {
    // 子iframe发送消息给父页面
    window.parent.postMessage({task: "barColorMessage", barColor: "#000"}, "*");
}, 200);












